#include "client.h"
#include <QtNetwork>
#include <QMessageBox>

Client::Client(QTcpSocket * socket, QObject *parent)
        : QThread(parent)
{
    NickName = QString();
    tcpSocket = socket;
    //connect(tcpSocket, SIGNAL(disconnected()), tcpSocket, SLOT(deleteLater()));
    connect( tcpSocket, SIGNAL(disconnected()), this, SLOT(End()) );
    connect( this, SIGNAL(newToWrite()), this, SLOT(SendToClient()) );
    connect( tcpSocket, SIGNAL(readyRead()), this, SLOT(ReadFromClient()) );

}

void Client::run()
{




    //while(true)
    //{
        //if(this->isFinished())
        //    break;
        msleep(10);
    //}
        exec();


}

QString Client::Read()
{
    QString return_ = readBuffer;
    readBuffer.clear();

    return return_;
}

void Client::Write(QString string)
{
    writeBuffer.append(string);

    emit newToWrite();
}

void Client::ReadFromClient()
{
    readBuffer.append(QString(tcpSocket->readAll()) );
    //QMessageBox::information(0, QString("info"), QString().append(readBuffer) );
    emit newToRead();
}

void Client::SendToClient()
{
    //QMessageBox::information(0, QString("info"), QString().append(writeBuffer).append(tcpSocket->peerAddress().toString()) );
    QByteArray block;
    block.append( writeBuffer.toUtf8() );
    tcpSocket->write(block);
    tcpSocket->flush();
    writeBuffer.clear();
}

void Client::End()
{
    tcpSocket->disconnectFromHost();
    tcpSocket->waitForDisconnected();
    this->exit();
}

QHostAddress Client::getPeerAddress()
{
    return tcpSocket->peerAddress();
}
